<?php
/**
* This file holds a class for Application_Model_BusLineToBusStopMapper.
* @package busmap
*/

/**
* This class holds Application_Model_BusLineToBusStopMapper class, that maps BusLineToBusStopMapper objects to the database entries.
* @package busmap
*/
class Application_Model_BusLineToBusStopMapper
{
	protected $_dbTable;

 	/**
	* Function that sets the database table for the BusLineToBusStop objects.
	*/
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
 
  	/**
	* Function that gets the database table for the BusLineToBusStop objects.
	*/
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_BusLineToBusStop');
		}
		return $this->_dbTable;
	}

	/**
	* Function that gets an array of buslineToBusstop objects and inserts each object as a new entry.
	* This function will be called when adding a new busline with many busstops.
	*/
	public function saveMany($buslineToBusstopArr){
		foreach($buslineToBusstopArr as $buslineToBusstop){
			$data = array(
				'busLine_id'   => $buslineToBusstop->getBusLineId(),
				'busStop_id' => $buslineToBusstop->getBusStopId(),
				'tableOrder' => $buslineToBusstop->getTableOrder()
			);
			$this->getDbTable()->insert($data);
		}
	}
 
	/**
	* Function that saves the given BusLineToBusStop object to the database.
	* If the id of the object is null, then a new entry will be inserted.
	* Upon insertion other entries that have the same busLine_id and greater or equal tableOrder value, will have their tableOrder increased by 1.
	*  This allows for the insertion of entries between other entries while maintaining a strictly growing tableOrder on that busline.
	* If is is speficied and the busstop id is set to 0, then the entry will be deleted.
	*/
	public function save(Application_Model_BusLineToBusStop $buslineToBusstop)
	{
		$data = array(
			'busLine_id'   => $buslineToBusstop->getBusLineId(),
			'busStop_id' => $buslineToBusstop->getBusStopId()
		);
 
		if (null == ($id = $buslineToBusstop->getId())) {

			
			if($buslineToBusstop->getBusLineAfterId() != -1){
				$where = array($this->getDbTable()->getAdapter()->quoteInto('id = ?', $buslineToBusstop->getBusLineAfterId()));
				$lastOrder = $this->getDbTable()->fetchAll($where);
				foreach($lastOrder as $lastOrderRow){
					$data['tableOrder'] = $lastOrderRow->tableOrder +1;
				}
			}else{
				$data['tableOrder'] = 0;
			}
				
			
			$lastId = $this->getDbTable()->insert($data);

			try{
				$where = array(
						'busLine_id = ?'=>$data['busLine_id'],
						'tableOrder >= ?'=>$data['tableOrder'],
						'id != ?'=>$lastId
					);

				$updateOrders = $this->getDbTable()->fetchAll($where);
				foreach($updateOrders as $updateOrder){
					$updateData = array('tableOrder' => $updateOrder->tableOrder + 1);
					$where = array('id = ?' => $updateOrder->id);
					$this->getDbTable()->update($updateData, $where);
				}
									

			}catch(Exception $e){
				print_r( $e->getMessage());
				die();
			}
		} else {
			if($buslineToBusstop->getBusStopId() == 0){
				$where = $this->getDbTable()->getAdapter()->quoteInto('id = ?', $id);
				$this->getDbTable()->delete($where);
			}else{
				//don't change a thing
			}
		}
	}
 
	/**
	* This function finds a BusLineToBusStop entry with the given id and sends it to the given buslineToBusstop reference.
	*/
	public function find($id, Application_Model_BusLineToBusStop $buslineToBusstop)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$buslineToBusstop->setId($row->id)
				  ->setBusLineId($row->busLine_id)
				  ->setBusStopId($row->busStop_id)
				  ->setTableOrder($row->tableOrder);
	}

	/**
	* This function finds all busstops corresponding to the given busline id.
	* It returns an array of busStop objects in the ascending order of tableOrder values of the corresponding busLineToBusStop entries.
	*/
	public function findBusStops($busLineId){
		$resultSet = $this->getDbTable()->fetchAll(null, 'tableOrder ASC');
		$entries   = array();
		foreach ($resultSet as $row) {
			if($row->busLine_id == $busLineId){
				$busStops = new Application_Model_BusStopMapper();
				$entry = new Application_Model_BusStop();
				$busStops->find($row->busStop_id, $entry);
				$entries[] = array($entry, $row->id);
			}
		}
		return $entries;

	}

	/**
	* This function finds all buslines corresponding to the given busstop id.
	* It returns an array of busLine objects in the ascending order of tableOrder values of the corresponding busLineToBusStop entries.
	*/
	public function findBusLines($busStopId){
		$resultSet = $this->getDbTable()->fetchAll(null, 'tableOrder ASC');
		$entries   = array();
		$usedIds = array();
		foreach ($resultSet as $row) {
			if($row->busStop_id == $busStopId){
				$busLines = new Application_Model_BusLineMapper();
				$entry = new Application_Model_BusLine();
				$busLines->find($row->busLine_id, $entry);
				if($entry->id && !in_array($entry->id, $usedIds)){
					$usedIds[] = $entry->id;
					$entries[] = $entry;
				}
			}
		}
		return $entries;

	}
 
	/**
	* This returns all busLineToBusStop entries in the ascending order of the tableOrder value.
	*/
	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll(null, 'tableOrder ASC');
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_BusLineToBusStop();
			$entry->setId($row->id)
				  ->setBusLineId($row->busLine_id)
				  ->setBusStopId($row->busStop_id)
				  ->setTableOrder($row->tableOrder);
		}
		return $entries;
	}
}